<?php

class Sistema_CursoController extends App_Controller_Action
{
    private $_table     = 'CURSO';
    private $_pk        = 'CUR_ID';
    private $_order_col = 'CUR_ID';
    private $_order     = 'ASC';
    private $_sta_col   = 'CUR_STA';
    private $obj        = '';
    private $form       = '';
    private $_file_col  = 'CUR_FILE'; 
    public  $dir        = 'public/upload/curso/'; 
    
    public function init()
    {
        $this->obj = new Sistema_Model_DbTable_Curso();
        //if($this->getRequest()->getActionName() == 'edit') $this->form = new Sistema_Form_Curso();
    }

    public function indexAction() {
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('operacoes','library');
        Zend_Loader::loadClass('dominio','library');
        Zend_Loader::loadClass('elemform','library');
        
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_curso_list.js');
        
        $where = 'c.'.$this->_pk . ' > 0';
        
        $stafiltro = $filtro = $this->_getParam('stafiltro', '1'); 
        if($stafiltro != '') $where .= ' and c.CUR_STA = ' . $stafiltro;
        $this->view->stafiltro  = $stafiltro;
        
        $itfiltro = $this->_getParam('itfiltro', ''); 
        if($itfiltro != '') $where .= ' and n.NRT_NOM like "' . $itfiltro.'%"';
        $this->view->itfiltro = $itfiltro;
       
        //$STA = $this->_getParam($this->_sta_col, 1);
        //$where .= ' and ' . $this->_sta_col . ' = ' . $STA;
        
        //$result = $this->obj->fetchAll($this->obj->select()->where($where)->order($this->_order_col.' '.$this->_order));
        //$this->view->result = $this->paginacao($result,20);
        
        $query = 'SELECT SQL_CACHE c.*, cb.CBS_NOM, cb.CBS_TPOTMP, n.NRT_NOM FROM '.$this->_table.' c, CURSOBASE cb, NUMEROTURMA n WHERE c.CBS_ID = cb.CBS_ID AND c.CUR_TRM = n.NRT_ID AND '.$where.' ORDER BY n.NRT_SEM ASC, n.NRT_NOM ASC, c.'.$this->_order_col.' '.$this->_order;
        $result = $this->db->fetchAll($query);
        $this->view->result = $this->paginacao($result,20); 
    }
    
    public function editAction() {
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskMoney.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/jquery.maskedinput.min.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/mask.js');
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/validation/dist/jquery.validate.min.js');
        
        $this->view->headLink()->prependStylesheet($this->_urlbase.'/public/media/js/chosen/chosen.min.css'); 
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/chosen/chosen.jquery.min.js');
        
        $this->view->headScript()->appendFile($this->_urlbase.'/public/media/js/view/s_curso.js');
        
        Zend_Loader::loadClass('tools','library');
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('elemform','library');
        Zend_Loader::loadClass('dominio','library');
        
        $this->view->db = $this->db;
        
        //$this->view->form = $this->form;
        if($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            try {
                
                if(1){//$this->form->isValid($formData)) {
                    
                    $id = (int) $formData[$this->_pk];//$this->form->getValue($this->_pk);
                    
                    //$returnImg = imagem::upload($this->_file_col,$this->dir,$id,TRUE,100,100);                    
                    
                    $data = $formData;//$this->form->getValues();
                    
                    unset($data['FOR_ID']);
                    unset($data['submit']);
                    //unset($data[$this->_file_col]);
                    
                    //echo '<pre>'; echo print_r($data);
                    
                    if($data['CUR_TPOTMP'] != 2) $data['CUR_SEM'] = 0;
                    
                    $data['CUR_VLR'] = tools::money_to_float($data['CUR_VLR']); 
                    $data['CUR_DATPRO'] = Datetools::dma_amd($data['CUR_DATPRO']);
                    $data['CUR_PERDSC'] = tools::money_to_float($data['CUR_PERDSC']); 
                    $data['CUR_VLRPRO'] = tools::money_to_float($data['CUR_VLRPRO']); 
                    $data['CUR_DATINI'] = Datetools::dma_amd($data['CUR_DATINI']);
                    $data['CUR_DATFIM'] = Datetools::dma_amd($data['CUR_DATFIM']);
                    
                    if(isset($data['MTL_ID'])) $data['MTL_ID'] = implode(',', $data['MTL_ID']);
                   
                    //echo '<pre>'; echo print_r($data);exit();
                    
                    $this->db->beginTransaction();
                    
                    $erro = 0;
                    if ($id == 0){
                        $data['CUR_VAGMAT'] = $data['CUR_NMRMAXALU']; // vagas disponíveis
                        $data['CUR_STA'] = 1;
                        $this->db->insert('CURSO',$data);
                        $id =  $this->db->lastInsertId();
                        //imagem::rename($id,$this->dir,$returnImg['filenew']);
                    }
                    else {
                        
                        if(strtotime($data['CUR_DATFIM']) > strtotime(date('Y-m-d')) && !isset($data['CUR_STA'])){
                            $data['CUR_STA'] = 1;
                        }
                        
                        //$mat = new Sistema_Model_DbTable_Matricula();
                        //$r_mat = $mat->fetchRow($this->_pk.' = ' . $id.' and MAT_STA = 1');
                        //if($r_mat['MAT_ID'] <= 0){ // se tiver matricula não altera mais
                            $this->db->update('CURSO', $data, $this->_pk.' = ' . $id);
                            
                        //}
                        //else $erro = 1;
                            
                        if($data['CUR_STA'] == 1){
                            $query = 'SELECT SQL_CACHE CUR_ID FROM CURSO WHERE '.$this->_pk.' = ' . $id;
                            $result = $this->db->fetchAll($query);
                            foreach($result as $row){
                                 $this->db->update('MATRICULA',array('MAT_STA'=>'1'),'CUR_ID = ' . $row['CUR_ID']); 
                            }
                        }
                        
                    }
                 
                    $obj2 = new Sistema_Model_DbTable_Cursoforma(); 
                    $obj2->delete('CUR_ID = '.(int)$id);
                    foreach($formData['FOR_ID'] as $for)
                    {   
                        $data = array( 'CUR_ID'=> $id, 'FOR_ID'=> $for);
                        $obj2->insert($data);
                    }
                    
                    if(strlen($_FILES[$this->_file_col]['tmp_name']) > 1){
                        $img = glob($this->dir.$id.'.*');
                        foreach($img as $filetemp) $filename = $filetemp;
                        imagem::reizeFull($filename,$filename, '270', '270');
                    }
                    
                    /*
                    $obj2 = new Sistema_Model_DbTable_Cursoturno();
                    $obj2->delete('CUR_ID = '.(int)$id);
                    foreach($this->form->getValue('CRT_ID') as $tur)
                    {   
                        $data = array( 'CRT_ID'=> $tur, 'CUR_ID'=> $id);
                        $obj2->insert($data);
                    }
                    */
                    if($erro == 0){
                        $this->db->commit();
                        $this->_helper->redirector('index');
                    }
                    else echo '<script>alert("Curso não pode ser alterado. Matrículas já realizadas!");</script>';
                } else {
                    //$this->form->populate($formData);
                    $this->view->data = $formData;
                }
            } catch(Exception $ex) {
                Zend_Loader::loadClass('errordb','library');
                echo '<script>alert("'.$ex->getMessage().'");</script>';
                // echo $ex->getMessage();
                //$this->form->populate($formData);
                $this->view->data = $formData;
                $this->db->rollBack();
            }
        } else {
            
            $id = $this->_getParam('id', 0);
            if ($id > 0) {
                $data = $this->obj->fetchRow($this->_pk . ' = ' . $id)->toArray();
                $data['CUR_VLR'] = tools::float_to_money($data['CUR_VLR']); 
                $data['CUR_DATPRO'] = Datetools::amd_dma($data['CUR_DATPRO']);
                $data['CUR_VLRPRO'] = tools::float_to_money($data['CUR_VLRPRO']); 
                $data['CUR_PERDSC'] = tools::float_to_money($data['CUR_PERDSC']); 
                $data['CUR_DATINI'] = Datetools::amd_dma($data['CUR_DATINI']);
                $data['CUR_DATFIM'] = Datetools::amd_dma($data['CUR_DATFIM']);
                //$this->form->populate($data);
                $this->view->data = $data;
                
                
                $query = 'SELECT SQL_CACHE MAT_ID	 FROM MATRICULA WHERE '.$this->_pk.' = ' . $id;
                $row = $this->db->fetchRow($query);
                if($row['MAT_ID	'] > 0){
                    $this->view->status = FALSE;
                }else{
                    $this->view->status = TRUE;
                }
            }
        }
    }

    public function deleteAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('id', 0);
        if ((int)$id > 0 ){   
            
            $this->db->beginTransaction();
            try {
                //$for = new Sistema_Model_DbTable_Cursoforma();
                //$for->delete($this->_pk . ' = ' . $id);
                //$this->obj->delete($this->_pk . ' = ' . $id);
                $ok = (bool) $this->db->delete('CURSO_FORMA', $this->_pk . ' = ' . $id); 
                $ok = (bool) $this->db->delete($this->_table, $this->_pk . ' = ' . $id); 
                $this->db->commit();
            } catch(Exception $ex) {
                //echo getMessage();
                $ok = FALSE;
                $msg = 'Não é possivel deleter o registro. Existem matrículas para esse grupo!';
                $this->db->rollBack();
            }          
        }       
        echo json_encode(array('ok' => $ok ,'msg'=>$msg));
    }
    
    public function buscacursobaseAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $id = $this->_getParam('cbs_id', 0);
        $cur_id = $this->_getParam('cur_id', 0);
        $cur_sem = $this->_getParam('cur_sem', '');
        $cur_ano = $this->_getParam('cur_ano', date('Y'));
        
        Zend_Loader::loadClass('datetools','library');
        Zend_Loader::loadClass('dominio','library');
        
        if ((int)$id > 0 ){
            //$obj = new Sistema_Model_DbTable_Cursobase();
            //$data = $obj->fetchRow('CBS_ID = ' . $id);
            $query = 'SELECT SQL_CACHE * FROM CURSOBASE WHERE CBS_ID = ' . $id;
            $data = $this->db->fetchRow($query);
            
            //$obj = new Sistema_Model_DbTable_Curso();
            //$data_cur = $obj->fetchRow('CUR_ID = ' . $cur_id);
            $query = 'SELECT SQL_CACHE * FROM CURSO WHERE CUR_ID = ' . $cur_id;
            $data_cur = $this->db->fetchRow($query);
            
            $arr= dominio::TipoSemestre();
            //$tipo_curso = $arr[$data['CBS_TPOTMP']];
            $tipo_curso = $arr[$data['CBS_TPOTMP']].'<input type="hidden" id="CUR_TPOTMP" name="CUR_TPOTMP" value="'.$data['CBS_TPOTMP'].'" />';
            
            $arr_cur = array();
            
            $where  = 'CUR_STA = 1 and CUR_ANO = '.$cur_ano;
            //não pode aparecer grupo se já foi usado em algum curso, por isso foi comentado 
            if($data_cur['CUR_ID'] > 0) $where  .= ' and CUR_ID <> '.$data_cur['CUR_ID'];
            //if($data['CBS_TPOTMP'] == 2 && $cur_sem > 0) $where  .= ' and CUR_SEM = '.$cur_sem;
            //semestre
            if($cur_sem > '') $where  .= ' and CUR_SEM = '.$cur_sem;
            	
            
            //$r_cur = $this->db->fetchAll('SELECT SQL_CACHE DISTINCT CUR_TRM, CURSO.* FROM CURSO WHERE '.$where);
            $query = 'SELECT SQL_CACHE DISTINCT CUR_TRM, CURSO.* FROM CURSO WHERE '.$where;
            $r_cur = $this->db->fetchAll($query);
            foreach($r_cur as $r_c) $arr_cur[$r_c['CUR_TRM']] = $r_c['CUR_TRM'];
            
            //$obj = new Sistema_Model_DbTable_Numeroturma();
            //$obj = $obj->fetchAll('NRT_STA = 1');
            $query = 'SELECT SQL_CACHE NRT_ID,NRT_NOM FROM NUMEROTURMA WHERE NRT_STA = 1 ORDER BY NRT_SEM ASC, NRT_HOR ASC';
            $obj = $this->db->fetchAll($query);
            
            $turma = '<select id="CUR_TRM" name="CUR_TRM" class="chosen-select" required=""><option value="">Nenhum</option>';
            foreach($obj as $r){   
                if(array_search($r['NRT_ID'], $arr_cur) === FALSE){
                    $select = $r['NRT_ID'] == $data_cur['CUR_TRM'] ? 'selected':''; 
                    $turma .= '<option '.$select.' value="'.$r['NRT_ID'].'">'.$r['NRT_NOM'].'</option>';
                }
            }
            $turma .= '</select><script> $(function(){ $(".chosen-select").chosen(); }); </script>';
            
           echo json_encode(array('ok' => TRUE,'CUR_TPOTMP'=>$data['CBS_TPOTMP'],
                'tipo_curso'=>$tipo_curso, 'turma' =>$turma, 'CUR_SEM'=>$cur_sem,
               ));
            
        }
        else echo json_encode(array('ok' => $ok));
    }
    
    
    public function buscahorarioturmaAction() {
        $this->_helper->layout->disableLayout(); 
        $this->_helper->viewRenderer->setNoRender();  
        $ok = FALSE;
        $html = '';
        $id = $this->_getParam('id', 0);
        
        Zend_Loader::loadClass('datetools','library');
        
        if ((int)$id > 0 ){
            $ok = TRUE;
            $obj = new Sistema_Model_DbTable_Numeroturma();
            $obj = $obj->fetchRow('NRT_ID = '.$id);
            $html = '<div class="ln" style="margin-top: 10px;"><strong></strong> '.Datetools::semana($obj['NRT_SEM'],2).' '.substr($obj['NRT_HOR'],0,5).'</div>';
        }
        
        echo json_encode(array('ok' => $ok,'html'=>$html));
    }
}

